package com.yunchao.app.presentation.main

import androidx.lifecycle.viewModelScope
import com.yunchao.app.domain.repository.NavHostRepository
import com.yunchao.feature.base.data.CustomAudioManager
import com.yunchao.feature.base.domain.result.errorMsg
import com.yunchao.feature.base.presentation.viewmodel.BaseEffect
import com.yunchao.feature.base.presentation.viewmodel.BaseState
import com.yunchao.feature.base.presentation.viewmodel.BaseViewModel
import kotlinx.coroutines.launch

internal class NavHostViewModel(
    private val navHostRepository: NavHostRepository,
    private val customAudioManager: CustomAudioManager,
) : BaseViewModel<NavHostViewModel.UiState, Nothing, NavHostViewModel.UiEffect>(
    UiState.Idle
) {

    // region [Public API]
    fun openDevice() = viewModelScope.launch {
        postSideEffect(UiEffect.ShowLoading)
        navHostRepository.openDevice()
            .onSuccess {
                postSideEffect(UiEffect.ShowDialog("设备初始化成功"))
                customAudioManager.playSound(1)
                postSideEffect(UiEffect.HideLoading)
            }
            .onFailure {
                postSideEffect(UiEffect.ShowToast(it.errorMsg))
                postSideEffect(UiEffect.HideLoading)
            }
    }

    fun closeDevice() = viewModelScope.launch {
        navHostRepository.closeDevice()
    }
    // endregion


    override fun onCleared() {
        closeDevice()
        super.onCleared()
    }

    internal sealed interface UiState : BaseState {
        data object Idle : UiState
    }

    internal sealed interface UiEffect : BaseEffect {
        data object ShowLoading : UiEffect
        data object HideLoading : UiEffect
        data class ShowToast(val msg: String) : UiEffect
        data class ShowDialog(val msg: String) : UiEffect
    }
}